package cn.stylefeng.guns.modular.gridsystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.stylefeng.guns.core.context.login.LoginContextHolder;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.core.factory.PageFactory;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.modular.gridsystem.entity.BizDevice;
import cn.stylefeng.guns.modular.gridsystem.entity.BizGateway;
import cn.stylefeng.guns.modular.gridsystem.entity.BizStation;
import cn.stylefeng.guns.modular.gridsystem.enums.BizStationsExceptionEnum;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizDeviceMapper;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizGatewayMapper;
import cn.stylefeng.guns.modular.gridsystem.mapper.BizStationMapper;
import cn.stylefeng.guns.modular.gridsystem.model.param.BizStationParam;
import cn.stylefeng.guns.modular.gridsystem.model.result.BizStationResult;
import cn.stylefeng.guns.modular.gridsystem.service.BizStationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 站点表 服务实现类
 *
 * @author ssy
 * @date 2021/09/14 11:47
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BizStationServiceImpl extends ServiceImpl<BizStationMapper, BizStation> implements BizStationService {


    private final BizGatewayMapper gatewayMapper;

    private final BizDeviceMapper deviceMapper;

    @Override
    public PageResult<BizStationResult> page(BizStationParam param) {

        boolean superAdmin = LoginContextHolder.me().isSuperAdmin();
        LambdaQueryWrapper<BizStation> queryWrapper = new LambdaQueryWrapper<BizStation>()
                .like(ObjectUtil.isNotEmpty(param.getStationName()), BizStation::getStationName, param.getStationName())
                .orderByDesc(BizStation::getCreateTime);

        if (superAdmin) {
            return new PageResult<>(this.baseMapper.pageAllList(PageFactory.defaultPage(), queryWrapper));
        } else {
            List<Long> list = LoginContextHolder.me().getLoginUserDataScopeIdList();
            // 查询分页结果
            return new PageResult<>(this.baseMapper.pageList(PageFactory.defaultPage(), param, list));
        }

    }

    @Override
    public PageResult<BizStationResult> pageList(BizStationParam bizStationParam) {
        LambdaQueryWrapper<BizStation> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(bizStationParam)) {
            if (ObjectUtil.isNotEmpty(bizStationParam.getOrgId())) {
                queryWrapper.eq(BizStation::getOrgId, bizStationParam.getOrgId());
            }
        }

        Page<BizStation> page = this.page(PageFactory.defaultPage(), queryWrapper);
        List<BizStationResult> stationResults = page.getRecords()
                .stream()
                .map(item -> BeanUtil.toBean(item, BizStationResult.class))
                .collect(Collectors.toList());
        PageResult<BizStationResult> pageResult = new PageResult<>();
        pageResult.setRows(stationResults);
        pageResult.setTotalRows(Convert.toInt(page.getTotal()));
        pageResult.setPageNo(Convert.toInt(page.getCurrent()));
        pageResult.setPageSize(Convert.toInt(page.getSize()));
        pageResult.setTotalPage(PageUtil.totalPage(Convert.toInt(page.getTotal()),
                Convert.toInt(page.getSize())));
        pageResult.setRainbow(PageUtil.rainbow(Convert.toInt(page.getCurrent()),
                Convert.toInt(pageResult.getTotalPage()), PageResult.RAINBOW_NUM));
        return pageResult;
    }


    @Override
    public List<BizStationResult> list(BizStationParam bizStationParam) {
        boolean superAdmin = LoginContextHolder.me().isSuperAdmin();
        if (superAdmin) {
            // 构造条件
            return this.list(new LambdaQueryWrapper<BizStation>())
                    .stream()
                    .map(item -> BeanUtil.toBean(item, BizStationResult.class))
                    .collect(Collectors.toList());
        } else {
            List<Long> list = LoginContextHolder.me().getLoginUserDataScopeIdList();
            // 查询分页结果
            return this.baseMapper.listByOrgIds(list,bizStationParam);
        }

    }

    @Override
    public void add(BizStationParam bizStationParam) {
        // 将dto转为实体
        BizStation bizStation = new BizStation();
        BeanUtil.copyProperties(bizStationParam, bizStation);
        Long sysLoginUserOrgId = LoginContextHolder.me().getSysLoginUserOrgId();
        boolean superAdmin = LoginContextHolder.me().isSuperAdmin();
        if (!superAdmin) {
            bizStation.setOrgId(sysLoginUserOrgId);
        }
        this.save(bizStation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(BizStationParam param) {

        BizStation station = this.queryBizStation(param);

        // 查询是否有关联网关
        if (gatewayMapper.selectCount(new LambdaQueryWrapper<BizGateway>().eq(BizGateway::getStationId, station.getId())) > 0) {
            log.warn("站点下面存在网关，不允许删除，站点主键为：{}", station.getId());
            throw new ServiceException(BizStationsExceptionEnum.HAVE_GATEWAY_NOT_ALLOWED_DELETE);
        }

        // 查询是否有设备
        if (deviceMapper.selectCount(new LambdaQueryWrapper<BizDevice>().eq(BizDevice::getStationId, station.getId())) > 0) {
            log.warn("站点下面存在设备，不允许删除，站点主键为：{}", station.getId());
            throw new ServiceException(BizStationsExceptionEnum.HAVE_DEVICE_NOT_ALLOWED_DELETE);
        }

        // 删除数据
        this.removeById(param.getId());
    }

    @Override
    public void edit(BizStationParam bizStationParam) {
        Long sysLoginUserOrgId = LoginContextHolder.me().getSysLoginUserOrgId();
        // 根据id查询实体
        BizStation bizStation = this.queryBizStation(bizStationParam);

        // 请求参数转化为实体
        BeanUtil.copyProperties(bizStationParam, bizStation);
        boolean superAdmin = LoginContextHolder.me().isSuperAdmin();
        if (!superAdmin) {
            bizStation.setOrgId(sysLoginUserOrgId);
        }
        this.updateById(bizStation);
    }

    @Override
    public BizStation detail(BizStationParam bizStationParam) {
        return this.queryBizStation(bizStationParam);
    }


    /**
     * 获取站点表
     *
     * @author ssy
     * @since 2021/09/14 11:47
     */
    private BizStation queryBizStation(BizStationParam bizStationParam) {
        BizStation bizStation = this.getById(bizStationParam.getId());
        if (ObjectUtil.isEmpty(bizStation)) {
            log.warn("站点不存在，站点主键为：{}", bizStationParam.getId());
            throw new ServiceException(BizStationsExceptionEnum.NOT_EXIST);
        }
        return bizStation;
    }
}
